package com.wish.g04.financing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.g04.base.entity.Business;
import com.wish.g04.base.entity.CwPaymentPlan;
import com.wish.g04.base.entity.SfContract;
import com.wish.g04.base.service.IBusinessService;
import com.wish.g04.base.service.ICwPaymentPlanService;
import com.wish.g04.base.service.ISfContractService;
import com.wish.g04.common.core.utils.StringUtils;
import com.wish.g04.common.security.utils.SecurityUtils;
import com.wish.g04.financing.dto.ItemTypeDTO;
import com.wish.g04.financing.dto.PaymentPlanDTO;
import com.wish.g04.financing.mapper.OrderNoMapper;
import com.wish.g04.financing.service.PaymentPlanService;
import com.wish.g04.financing.vo.PaymentDayVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 付款计划ServiceImpl
 * @author tianyandong
 */
@Service
public class PaymentPlanServiceImpl implements PaymentPlanService {

    @Autowired
    private ICwPaymentPlanService iCwPaymentPlanService;

    @Autowired
    private ISfContractService iSfContractService;

    @Autowired
    private IBusinessService iBusinessService;

    @Autowired
    private OrderNoMapper orderNoMapper;

    /**
     * 收房合同的查询
     * @param sfContract
     * @return
     */
    @Override
    public List<SfContract> getHouseContractList(SfContract sfContract) {
        QueryWrapper<SfContract> queryWrapper = new QueryWrapper<>();
        //状态未删除的
        queryWrapper.eq("del_flg",0);
        //续约状态：已续约不能查到
        queryWrapper.eq("xy_status",0);
        //合同状态为：已提交
        queryWrapper.eq("status",2);
        //小区名称
        if (StringUtils.isNotEmpty(sfContract.getPremiseName())) {
            queryWrapper.like("premise_name",sfContract.getPremiseName());
        }
        //业主姓名
        if (StringUtils.isNotEmpty(sfContract.getOwnerName())) {
            queryWrapper.like("owner_name",sfContract.getOwnerName());
        }
        List<SfContract> sfContractList = iSfContractService.list(queryWrapper);
        return sfContractList;
    }

    /**
     * 根据id收房合同
     * @param id
     * @return
     */
    @Override
    public SfContract getHouseContractById(Long id) {
        return iSfContractService.getById(id);
    }

    /**
     * 获取可选择的账期
     * @param id
     * @return
     */
    @Override
    public List<PaymentDayVO> getPaymentDayVOList(Long id) {
        ArrayList<PaymentDayVO> paymentDayVOList = new ArrayList<>();
        QueryWrapper<CwPaymentPlan> queryWrapper = new QueryWrapper<>();
        if (null != id) {
            queryWrapper.eq("contract_id",id);
        }
        //条件为收房
        queryWrapper.eq("contract_type",1);
        //条件为租金
        queryWrapper.eq("item_type",3);
        List<CwPaymentPlan> paymentPlanList = iCwPaymentPlanService.list(queryWrapper);
        paymentPlanList.forEach(cwPaymentPlan -> {
            PaymentDayVO paymentDayVO = new PaymentDayVO();
            paymentDayVO.setPaymentId(cwPaymentPlan.getId())
                        .setPaymentDaysBegin(cwPaymentPlan.getPaymentDaysBegin())
                        .setPaymentDaysEnd(cwPaymentPlan.getPaymentDaysEnd())
                        .setPayNumber(cwPaymentPlan.getPayNumber());
            paymentDayVOList.add(paymentDayVO);
        });
        return paymentDayVOList;
    }

    /**
     * 添加付款计划
     * @param paymentPlanDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePaymentPlan(PaymentPlanDTO paymentPlanDTO) {
        //获取登陆的用户id
        Long userId = SecurityUtils.getUserId();
        //获取登陆的用户名
        String username = SecurityUtils.getUsername();
        //根据用户id获取商户的id
        Business business = iBusinessService.getOne(new QueryWrapper<Business>().eq("user_id", userId));
        CwPaymentPlan cwPaymentPlan = new CwPaymentPlan();
        BeanUtils.copyProperties(paymentPlanDTO,cwPaymentPlan);
        //生产付款单号
        String type="FKJH";
        int random = (int) ((Math.random()*9+1)*1000);
        //查询生产的部分付款单号
        String result = orderNoMapper.getOrderNo(type);
        result = type + result + random;
        cwPaymentPlan.setCreateUserid(userId)
                .setOperationUser(username)
                .setBusinessId(Long.valueOf(business.getId()))
                .setPayOrderNo(result)
                .setUpdateUserid(userId)
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                //合同类型 : 1：收房合同， 2：出房合同
                .setContractType(1)
                //账单类型（金融属性）(1：收房贷变更,2：退租变更,3：普通账单(正常收房租务计划))
                .setBillType(3)
                //付款类型（1:收房付款单 2：租务付款单 3：解约结算收款）
                .setPayType(2);
        //添加

        boolean save = false;
        List<ItemTypeDTO> itemTypeDTOList = paymentPlanDTO.getItemTypeDTOList();
        System.out.println(itemTypeDTOList);
        if (!CollectionUtils.isEmpty(itemTypeDTOList)) {
            for (ItemTypeDTO itemTypeDTO : itemTypeDTOList) {
                if (null != itemTypeDTO.getPaymentAmount()) {
                    cwPaymentPlan.setItemType(itemTypeDTO.getItemType())
                            .setPaymentAmount(itemTypeDTO.getPaymentAmount())
                            .setRealPaymentAmount(itemTypeDTO.getRealPaymentAmount());
                    save = iCwPaymentPlanService.save(cwPaymentPlan);
                }
            }
        }
        return save;
    }
}
